package cn.itcast.nems.journal.service.impl;

import cn.hutool.core.lang.Assert;
import cn.itcast.ic.common.exception.v2.BizExceptionProducer;
import cn.itcast.nems.common.enumeration.NemsErrorBodyEnum;
import cn.itcast.nems.journal.dto.JournalRenewalCountDTO;
import cn.itcast.nems.journal.service.JournalRenewalOrderRelationshipService;
import cn.itcast.nems.journal.service.JournalRenewalPaidService;
import cn.itcast.nems.studentrecord.dao.entity.JournalRenewal;
import cn.itcast.nems.studentrecord.dao.entity.JournalRenewalOrderRelationship;
import cn.itcast.nems.studentrecord.dao.mapper.JournalRenewalMapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 升级凭单支付相关业务接口实现
 * </p>
 *
 * @author zhouwei
 * @since 2023/12/20 11:20 AM
 **/
@Service
@RequiredArgsConstructor
@Slf4j
public class JournalRenewalPaidServiceImpl implements JournalRenewalPaidService {
    private final JournalRenewalMapper journalRenewalMapper ;
    private final JournalRenewalOrderRelationshipService journalRenewalOrderRelationshipService;

    public JournalRenewalCountDTO findJournalIds(String recordId )  {
        List<JournalRenewalOrderRelationship> orderRelationshipList = journalRenewalOrderRelationshipService.findListByRecordId(recordId);
        Assert.notEmpty(orderRelationshipList, BizExceptionProducer.produce(NemsErrorBodyEnum.DATA_EXIST, "学籍ID：" + recordId + " 对应升级凭单订单关系"));
        JournalRenewalOrderRelationship orderRelationship = orderRelationshipList.get(0) ;
        List recordIds =  journalRenewalOrderRelationshipService.findRecordIdsByRenewalId(orderRelationship.getJournalRenewalId());
        return  new JournalRenewalCountDTO(recordIds ,orderRelationship.getJournalRenewalId() ) ;
    }

    @Override
    public void updatePaidNumber(String renewalId , Integer count) {
        JournalRenewal journalRenewal  = journalRenewalMapper.selectById(renewalId) ;
        Assert.notNull(journalRenewal , BizExceptionProducer.produce(NemsErrorBodyEnum.DATA_EXIST ,"升级凭单ID：" + renewalId)) ;
        if (Objects.nonNull(count)) {
            int updateResult = journalRenewalMapper.update(null,
                    new LambdaUpdateWrapper<JournalRenewal>().eq(JournalRenewal::getId,renewalId ).set(JournalRenewal::getPaidQuantity, count));
            Assert.isTrue(updateResult > 0, BizExceptionProducer.produce(NemsErrorBodyEnum.DATABASE_UPDATE_ERROR, "学籍支付回调统计凭单ID：" + renewalId + "已缴费人数"));
        }
    }
}
